﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace App
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            string querySql = "SELECT Id,AccountName,ConsumeDateTime,SaveMoneyTotal,CostTotal,(IFNULL(SaveMoneyTotal,0) - CostTotal) AS Balance,"
                            + " (SELECT ci.ImagePath FROM Consume AS ci WHERE ci.InsertDateTime = t.ConsumeDateTime) AS ImagePath,"
                            + " (SELECT cc.Cost FROM Consume AS cc WHERE cc.InsertDateTime = t.ConsumeDateTime AND cc.AccountId = t.Id) AS Cost"
                            + " FROM (SELECT Id,AccountName,"
                            + " (SELECT SUM(SaveMoney) FROM Income WHERE AccountId = a.Id) AS SaveMoneyTotal,"
                            + " (SELECT SUM(Cost) FROM Consume WHERE AccountId = a.Id) as CostTotal,"
                            + " (SELECT max(InsertDateTime) FROM Consume) as ConsumeDateTime"
                            + " FROM Account AS a) AS t";

            DataSet ds = DbHelperSQLite.Query(querySql);
            if (ds != null && ds.Tables != null && ds.Tables[0].Rows != null)
            {
                this.gvList.DataSource = DbHelperSQLite.Query(querySql).Tables[0];
                this.gvList.DataBind();
            }
            else
            {
                //无数据
            }
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvList.PageIndex = e.NewPageIndex;
            LoadData();
        }

        public static string ConvertDisplayValue(object value)
        {
            if (value == null || value is DBNull)
            {
                return "0";
            }
            else
            {
                //表中存储的是分，无小数点
                return Convert.ToString(Math.Round(Convert.ToInt32(value) / 100.00, 2));
            }

        }
    }
}